
//  UIButton+extension.swift
//
//  Created by laichunhui on 15/10/13.
//  Copyright © 2015年 lch. All rights reserved.
//
import UIKit
import Kingfisher

// 扩展中不允许编写指定构造函数！只能添加便利构造函数
// extension 不能定义`存储型`属性！
extension UIButton {
    
   /** initialize a button on normal and highlight state with imageName and  backGroundImageName.  */
    convenience init(imageName: String, backImageName: String?) {
        // 实例化按钮
        self.init()
        
        // 设置按钮属性
        setImage(UIImage(named: imageName), forState: UIControlState.Normal)
        setImage(UIImage(named: imageName + "_highlighted"), forState: UIControlState.Highlighted)
        
        if backImageName != nil {
            setBackgroundImage(UIImage(named: backImageName!), forState: UIControlState.Normal)
            setBackgroundImage(UIImage(named: backImageName! + "_highlighted"), forState: UIControlState.Highlighted)
        }
        
        // 自动调整大小
        sizeToFit()
    }
    
    /** initialize a button on normal state with title content and fontSize and titleColor and  backGroundImageName.  */
    convenience init(title: String, fontSize: CGFloat, titleColor: UIColor, backGroundImageName: String) {
        self.init()
        
        setTitle(title, forState: UIControlState.Normal)
        setBackgroundImage(UIImage(named: backGroundImageName), forState: UIControlState.Normal)
        setTitleColor(titleColor, forState: UIControlState.Normal)
        
        titleLabel?.font = UIFont.systemFontOfSize(fontSize)
    }
    
    /** initialize a  button on normal state with title content and fontSize and titleColor and imageName. */
    convenience init(title: String, fontSize: CGFloat, titleColor: UIColor, imageName: String) {
        self.init()

        setTitle(title, forState: UIControlState.Normal)
        setImage(UIImage(named: imageName), forState: UIControlState.Normal)
        setTitleColor(titleColor, forState: UIControlState.Normal)
        
        titleLabel?.font = UIFont.systemFontOfSize(fontSize)
    }
}

//MARK: 利用Kingfisher设置button
extension UIButton {
    /**  Set an image with border to use for a specified state with a URL and a placeholder image. */
    func vo_setImageWithURL(URL: NSURL, forState: UIControlState, placeholderImage: UIImage?, boderColor: UIColor, borderWidth: CGFloat) {
        
        let placeholder = UIImage.imageWithClipImage(placeholderImage!, borderWidth: borderWidth, borderColor: boderColor)
        
        kf_setImageWithURL(URL, forState: forState, placeholderImage: placeholder, optionsInfo: [.Transition(ImageTransition.Fade(1))]) { (image, error, cacheType, imageURL) -> () in
            
            self.setImage(UIImage.imageWithClipImage(image!, borderWidth: borderWidth, borderColor: boderColor), forState: .Normal)
        }
      
    }
}